import subprocess
import time
import tkinter as tk
from tkinter import Tk, filedialog, messagebox, simpledialog
import pymupdf  # pymupdf


def merge_pdfs(input_files, output_file):
    """
    将多个PDF文件合并为一个临时PDF
    """
    try:
        writer = pymupdf.open()
        for file in input_files:
            if not file or not file.strip():  # 检查文件路径是否有效
                raise ValueError("文件路径无效")
            doc = pymupdf.open(file)
            writer.insert_pdf(doc)
        writer.save(output_file)
        writer.close()
    except Exception as e:
        messagebox.showerror("错误", f"合并PDF失败: {str(e)}")

def combine_pages(input_file, output_file):
    try:
        # 定义A4尺寸（单位：毫米 转换为像素，300dpi）
        width, height = pymupdf.paper_size("a4")  # A4 portrait output page format
        r1 = pymupdf.Rect(0, 0, width, height / 2)
        r2 = pymupdf.Rect(0, height / 2, width, height)
        r_tab = [r1, r2]
        # 打开输入PDF文件
        doc = pymupdf.open(input_file)  # type: pymupdf.Document
        writer = pymupdf.open()  # type: pymupdf.Document
        
        # now copy input pages to output
        for spage in doc:
            if spage.number is None:
                raise ValueError("输入PDF文件无效，页面读取为空！")
            if spage.number % 2 == 0:  # create new output page
                page = writer.new_page(-1,      # type: ignore
                            width = width,
                            height = height)
            # insert input page into the correct rectangle
            page.show_pdf_page(r_tab[spage.number % 2],  # select output rect
                            doc,  # input document
                            spage.number)  # input page number
        # 保存最终PDF
        writer.save(output_file, garbage=3, deflate=True)
        writer.close()
        doc.close()
    except Exception as e:
        messagebox.showerror("错误", f"处理PDF页面失败: {str(e)}")

def select_files():
    files = filedialog.askopenfilenames(filetypes=[("PDF files", "*.pdf")])
    if files:
        file_list.delete(0, tk.END)
        for file in files:
            file_list.insert(tk.END, file)

def process_pdfs():
    input_files = file_list.get(0, tk.END)
    if not input_files:
        messagebox.showerror("错误", "请选择要合并的PDF文件")
        return
    temp_file = "merged.pdf"
    final_file = "combined.pdf"
    try:
        merge_pdfs(input_files, temp_file)
        combine_pages(temp_file, final_file)
        messagebox.showinfo("完成", "PDF处理完成，文件已保存为 combined.pdf")
    except Exception as e:
        messagebox.showerror("错误", f"处理PDF失败: {str(e)}")

def print_preview():
    # 这里可以调用系统的打印预览功能
    try:
        subprocess.Popen(['start', 'combined.pdf'], shell=True)
    except Exception as e:
        messagebox.showerror("错误", f"预览失败: {str(e)}")

# 创建主窗口
root = tk.Tk()
root.title("PDF合并工具")

# 创建文件列表框
file_list = tk.Listbox(root, width=80)
file_list.pack(pady=10)

# 创建按钮
select_button = tk.Button(root, text="选择文件", command=select_files)
select_button.pack(pady=5)

process_button = tk.Button(root, text="处理PDF", command=process_pdfs)
process_button.pack(pady=5)

preview_button = tk.Button(root, text="打印预览", command=print_preview)
preview_button.pack(pady=5)

PASSWORD = "1"  # 设置密码（建议用哈希存储）
EXPIRE_TIMESTAMP = 1746633600  # 密码过期时间戳（2025-06-01 00:00:00 UTC）

def verify_password_gui():
    root = Tk()
    root.withdraw()  # 隐藏主窗口
    pwd = simpledialog.askstring("启动验证", "请输入密码：", show='*')
    root.destroy()

    if time.time() > EXPIRE_TIMESTAMP:
        messagebox.showerror("错误", "密码已过期，请联系作者更新授权！")
        return False
    if pwd != PASSWORD:
        messagebox.showerror("错误", "密码错误！")
        return False
    return True

if __name__ == "__main__":
    # 运行主循环
    if not verify_password_gui():
        exit(1)
    root.mainloop()